/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.document.request;

import org.dopdf.document.model.Collection;
import org.dopdf.document.model.ConditionEvaluator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The class that is responsible to deligate the processing of the request to the right processor.
 *
 * @author Deep Shah
 */
public class RequestProcessorDeligate implements RequestProcessor {

    /**
     * The request processors configured in the application.
     */
    private final List<RequestProcessor> requestProcessors = new ArrayList<RequestProcessor>();

    /** The logger reference. */
    private static final Logger logger = Logger.getLogger(RequestProcessorDeligate.class.toString());

    /**
     * The constructor that will initialize all the request processors of the application.
     */
    public RequestProcessorDeligate() {
        requestProcessors.add(new StaticResourceRequestProcessor());
        requestProcessors.add(new DownloadDocumentRequestProcessor());
        requestProcessors.add(new PDFPageRequestProcessor());
    }

    /**
     * {@inheritDoc}
     */
    public boolean canProcess(final HttpServletRequest request) {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    public void process(final HttpServletRequest request, final HttpServletResponse response) {
        final RequestProcessor requestProcessor = new Collection<RequestProcessor>(requestProcessors).returnEntityIfConditionIsTrue(new ConditionEvaluator<RequestProcessor>() {
            /**
             * {@inheritDoc}
             */
            public boolean evaluate(final RequestProcessor entity) {
                return entity.canProcess(request);
            }
        });
        if(null == requestProcessor) {
            logger.log(Level.SEVERE, "No request processor found to process the request: " + request.getRequestURI());
            return;
        }
        requestProcessor.process(request, response);
    }
}
